package src.com.neusoft.nep.controller;

import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.stage.Stage;
import src.com.neusoft.nep.common.AQI;
import src.com.neusoft.nep.common.FileUtils;
import src.com.neusoft.nep.entity.ProvidedData;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

public class AQIDateDistributeTendController {
    @FXML
    private TableView<Map<String, String>> tableView;
    @FXML
    private DatePicker datePicker;
    @FXML
    private TableColumn<Map<String, String>, String> colnumber, colmonth, colaqi;

    private Stage currentStage;
    private ObservableList<Map<String, String>> tableList = FXCollections.observableArrayList();
    private AQI aqiAnalyzer = new AQI();
    private Map<String, ProvidedData> dataMap; // 存储读取的数据
    private final DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("yyyy-MM");

    public void setLoginViewStage(Stage stage) {
        this.currentStage = stage;
    }

    public void initialize() {
        // 设置表格列值工厂
        setupTableColumns();

        // 加载数据
        loadData();

        // 设置日期选择器默认值为当前日期
        datePicker.setValue(LocalDate.now());

        // 添加日期选择器值变更监听器
        datePicker.valueProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null) {
                loadMonthData(newValue);
            }
        });

        // 初始化加载当前日期所在月份的数据
        loadMonthData(datePicker.getValue());
    }

    private void setupTableColumns() {
        tableView.setItems(tableList);

        colnumber.setCellValueFactory(cellData -> {
            int index = cellData.getTableView().getItems().indexOf(cellData.getValue()) + 1;
            return new SimpleStringProperty(String.valueOf(index));
        });

        colmonth.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().get("month")));

        colaqi.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().get("exceedCount")));
    }

    private void loadData() {
        try {
            // 从文件读取数据
            dataMap = FileUtils.readMapObject("AdminData.txt");

            if (dataMap == null || dataMap.isEmpty()) {
                showEmptyMessage("无数据");
            }
        } catch (Exception e) {
            e.printStackTrace();
            showEmptyMessage("数据加载失败");
        }
    }

    // 加载所选日期所在月份的数据
    private void loadMonthData(LocalDate selectedDate) {
        tableList.clear();

        if (dataMap == null || dataMap.isEmpty()) {
            showEmptyMessage("无数据");
            return;
        }

        // 获取所选日期的年份和月份
        String monthKey = selectedDate.format(monthFormatter);

        // 计算该月超标天数
        int exceedCount = calculateExceedCountByMonth(selectedDate);

        // 创建表格行数据
        Map<String, String> row = new HashMap<>();
        row.put("month", monthKey);
        row.put("exceedCount", String.valueOf(exceedCount));

        tableList.add(row);
    }

    // 计算指定日期所在月份的超标天数
    private int calculateExceedCountByMonth(LocalDate date) {
        int year = date.getYear();
        int month = date.getMonthValue();
        int count = 0;

        for (ProvidedData data : dataMap.values()) {
            LocalDate dataDate = LocalDate.parse(data.getDate());

            // 检查是否属于所选月份
            if (dataDate.getYear() == year && dataDate.getMonthValue() == month) {
                double so2 = Double.parseDouble(data.getSo2());
                double co = Double.parseDouble(data.getCo());
                double pm = Double.parseDouble(data.getPm());

                // 计算各污染物等级
                int so2Level = aqiAnalyzer.getLevel(so2, "so2");
                int coLevel = aqiAnalyzer.getLevel(co, "co");
                int pmLevel = aqiAnalyzer.getLevel(pm, "pm");

                // 如果任一污染物等级≥3，则认为该日超标
                if (so2Level >= 3 || coLevel >= 3 || pmLevel >= 3) {
                    count++;
                }
            }
        }

        return count;
    }

    // 显示空数据提示
    private void showEmptyMessage(String message) {
        Map<String, String> emptyRow = new HashMap<>();
        emptyRow.put("month", "");
        emptyRow.put("exceedCount", message);
        tableList.add(emptyRow);
    }
}